package com.zw.cloud.common.utils;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import com.jhlabs.composite.ColorDodgeComposite;
import com.jhlabs.image.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;

public class ImgUtils {
    public static void main(String[] args) throws Exception {
        // 图像类型转换：GIF=》JPG、GIF=》PNG、PNG=》JPG、PNG=》GIF(X)、BMP=》PNG
        //ImgUtil.convert(FileUtil.file("e:/test2.png"), FileUtil.file("e:/test2Convert.jpg"));
        // gray 彩色转为黑白
        ImgUtil.gray(FileUtil.file("d:/1.jpg"), FileUtil.file("d:/11.png"));
        // 图片素描
        toSketch("d:/1.jpg", "d:/12.png");

    }

    private static void toSketch(String imgPath, String output) throws Exception {
        BufferedImage src = ImageIO.read(new File(imgPath));
        src = ImageUtils.convertImageToARGB(src);

        //图像灰度化
        PointFilter grayScaleFilter = new GrayscaleFilter();
        BufferedImage grayScale = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
        grayScaleFilter.filter(src, grayScale);

        //灰度图像反色
        BufferedImage inverted = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
        PointFilter invertFilter = new InvertFilter();
        invertFilter.filter(grayScale, inverted);

        //高斯模糊处理
        GaussianFilter gaussianFilter = new GaussianFilter(20);
        BufferedImage gaussianFiltered = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
        gaussianFilter.filter(inverted, gaussianFiltered);

        // 灰度图像和高斯模糊反向图混合
        ColorDodgeComposite cdc = new ColorDodgeComposite(1.0f);
        CompositeContext cc = cdc.createContext(inverted.getColorModel(), grayScale.getColorModel(), null);
        WritableRaster invertedR = gaussianFiltered.getRaster();
        WritableRaster grayScaleR = grayScale.getRaster();
        // 混合之后的就是我们希望的结果
        BufferedImage composite = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
        WritableRaster colorDodgedR = composite.getRaster();
        cc.compose(invertedR, grayScaleR, colorDodgedR);

        //输出做好的素描
        File outputfile = new File(output);
        ImageIO.write(composite, "png", outputfile);
    }

}
